package com.sky.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class RedisService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    // 写入数据
    public void setValue(String key, Object value, long timeout) {
        redisTemplate.opsForValue().set(key, value, timeout, TimeUnit.SECONDS);
    }
    // 写入数据
    public void setValue(String key, Object value) {
        redisTemplate.opsForValue().set(key, value);
    }

    // 读取数据
    public Object getValue(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    // 删除数据
    public void deleteValue(String key) {
        redisTemplate.delete(key);
    }
    @PostConstruct
    public void checkRedisConnection() {
        try {
            redisTemplate.opsForValue().get("test");
            log.info("Redis连接正常");
        } catch (Exception e) {
            log.error("Redis连接失败", e);
        }
    }
}
